package com.dragon.pear.modules.trade.common.config;

import com.dragon.common.spring.openapi.ApiGroup;
import com.dragon.common.spring.openapi.ClassTypeChecker;
import com.dragon.common.spring.openapi.ControllerImplementationFinder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springdoc.core.filters.OpenApiMethodFilter;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @author Chris Chan
 * Create On 2025/8/24 下午6:27
 * Use for: 自定义OpenApi方法过滤器
 * Explain:
 * 匹配分组标记
 */
@Component
public class MyOpenApiMethodFilter implements OpenApiMethodFilter {
    private static final Logger logger = LoggerFactory.getLogger(MyOpenApiMethodFilter.class);

    private CallBack callBack;
    @Override
    public boolean isMethodToInclude(Method method) {
        boolean result = false;
        Class<?> controllerClass = method.getDeclaringClass();

        if (ClassTypeChecker.isInterface(controllerClass) && method.isDefault()) {
            // 找到实际的实现类
            Class<?> implementationClass = ImplementationClassFinder.getInstance().findImplementationClass(method);
            if (implementationClass == null) {
                result = false;
            } else {
                controllerClass = implementationClass;
            }
        }

        // 用回调提供分组标记
        if (callBack == null) {
            return false;
        }
        String group = callBack.group();
        if (group == null || group.isEmpty()) {
            return false;
        }

        String foundGroup = findApiGroupFromClass(controllerClass);
        result = foundGroup != null && group.equals(foundGroup);
        logger.info("判断类 {} 是否支持分组 {}: {}", controllerClass.getName(), group, result);

        return result;
    }

    public MyOpenApiMethodFilter setCallBack(CallBack callBack) {
        this.callBack = callBack;
        return this;
    }

    /**
     * 从类中查找分组标记
     *
     * @param clazz
     * @return
     */
    public static String findApiGroupFromClass(Class<?> clazz) {
        // 优先检查类本身的注解
        if (clazz.isAnnotationPresent(ApiGroup.class)) {
            return clazz.getAnnotation(ApiGroup.class).value();
        }

        // 检查所有接口
        for (Class<?> interfaceClass : clazz.getInterfaces()) {
            if (interfaceClass.isAnnotationPresent(ApiGroup.class)) {
                return interfaceClass.getAnnotation(ApiGroup.class).value();
            }
        }

        // 检查父类
        Class<?> superclass = clazz.getSuperclass();
        if (superclass != null && superclass != Object.class) {
            String superGroup = findApiGroupFromClass(superclass);
            if (superGroup != null) {
                return superGroup;
            }
        }

        return null;
    }

    /**
     * 回调接口，用于获取分组信息
     */
    public interface CallBack {
        String group();
    }
}
